<?php
namespace app\common\process;

class PickUpCode extends Base {
	//获取核销码
	public function index() {
		$post = loader()->loadAny('request', 'jy\\PickUpCode')->index();
		$validate = loader()->loadAny('validate', 'jy\\PickUpCode');
		if(!$validate->scene('index')->check($post)) {
			$this->error($validate->getError());
		}
		$result = loadTool('PickUpCode')->get_code($post['id']);
		$this->assign($result);
		return $this->fetch();
	}

	//核销
	public function pick_up() {
		$post = loader()->loadAny('request', 'jy\\PickUpCode')->pick_up();
		$validate = loader()->loadAny('validate', 'jy\\PickUpCode');
		if(!$validate->scene('pick_up')->check($post)) {
			$this->error($validate->getError());
		}

		$only = loader()->loadAny('only', 'jy\\Order');
		$model = $only->getModel();
		try {
			$model->startTrans();
			$order = $only->get_row($post['id']);
			$order->status = loadEnum('OrderStatus')->code2key('yiwancheng');
			$order->save();
			$this->wechat_send_product($order, $post);
			$model->commit();
		} catch(\Exception $e) {
			$model->rollback();
			return $this->error($e->getMessage());
		}
		return $this->success('核销成功');
	}

	//通知微信小程序订单发货管理系统发货
    public function wechat_send_product($order, $post) {
        $app = loadTool('Wechat')->miniprogram();
        $openid = loadOnly('tyyh\\UserOpenid')->get_openid($order['route'], $order['uid']);

        $params= [
            "order_key" => [
                "order_number_type" => "2",
                "transaction_id" => $order['transaction_id'] // 支付流水号
            ],
            "logistics_type" => 4,
            "delivery_mode"  => 1,
            "shipping_list"  => [
                [
                    "item_desc"       => "支付编号--" . $order['out_trade_no']
                ]
            ],
            "upload_time" => date('Y-m-d\TH:i:sP'),
            "payer" => [
                "openid" => $openid// 用户openid
            ]
        ];

        $result = $app->shipping->uploadShippingInfo($params);
        if ($result['errcode'] != 0) {
            // 与微信服务器通信失败（如网络错误、参数格式错误）
            throw new \Exception($result['errmsg']);
        }
        return true;
    }
}
